package com.common.project.service.impl;

import com.common.project.converter.UserConverter;
import com.common.project.dto.UserDTO;
import com.common.project.exception.EntityNotFoundException;
import com.common.project.mapper.UserMapper;
import com.common.project.repository.UserRepository;
import com.common.project.service.RedisService;
import com.common.project.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.project.table.User;
import com.common.project.util.ValidationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.log4j.Log4j2;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import com.common.project.util.ExcelUtiles;
/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author jiangshicun
 * @since 2019-07-01
 */
@Service
@Log4j2
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserRepository userRepository;

    @Resource
    private UserConverter userConverter;

    @Autowired
    private RedisService redisService;


    @Override
    public String outPutMode(HttpServletResponse response) {
        String msg="";
        try {
            ExcelUtiles.exportExcel(new ArrayList<User>(),"用户表","用户表",User.class,"用户表模板.xls",true,response);
            msg="导出成功";
        } catch (Exception e) {
            log.error("操作异常: "+e.getMessage(),e);
            msg="导出异常";
        }
        return msg;
    }

    @Override
    public boolean inPutMode(MultipartFile file, HttpServletRequest request) {
        if(file.isEmpty()){
            return false;
        }
        try {
            List<User> Users = ExcelUtiles.importExcel(file, 0, 1, User.class);
            boolean save = this.saveBatch(Users);
            return save;
        } catch (Exception e) {
            log.error("操作异常: "+e.getMessage(),e);
            return false;
        }
    }


    @Override
    public UserDTO findByName(String userName) {
        User user = null;
        if(ValidationUtil.isEmail(userName)){
            user = userRepository.findByEmail(userName);
        } else {
            user = userRepository.findByUsername(userName);
        }
        if (user == null) {
            throw new EntityNotFoundException(User.class, "name", userName);
        } else {
            return userConverter.toDto(user);
        }
    }
}
